package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.MealCheckedAdapter;
import com.duowei.diandan.adapter.MealVAdapter;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.food.Meal;
import com.duowei.diandan.bean.food.MealChild;
import com.duowei.diandan.databinding.MealFragmentBinding;
import com.duowei.diandan.db.FoodMenu;
import com.duowei.diandan.db.entry.Tcsd;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.dialog.TasteDialogFragment;
import com.duowei.diandan.util.FoodHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class MealFragment extends Fragment {
    public static final String TAG = "MealFragment";

    private MealFragmentBinding mBinding;
    private Meal mMeal;

    private int mIndex = 0;

    private Observer mDataUpdateObserver = new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            FoodMenu.getInstance().queryMeal(mMeal.getMainTcsd().getXmbh1(), meal -> {
                mMeal = meal;
                setupView();
            });
        }
    };

    public static MealFragment newInstance(Meal meal) {

        Bundle args = new Bundle();
        args.putSerializable("meal", meal);

        MealFragment fragment = new MealFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mMeal = (Meal) getArguments().getSerializable("meal");
            if (mMeal != null) {
                mMeal.clearCheckedTaste();
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_meal, container, false);

        mBinding.backButton.setOnClickListener(v -> {
            if (mOnClickListener != null) {
                mOnClickListener.onCloseClick();
            }
        });

        mBinding.addButton.setOnClickListener(v -> {
            if (mOnClickListener != null) {
                if (mMeal.isAllChildChecked()) {
                    List<Tcsd> checkedTcsdList = mMeal.getCheckedList();
                    mIndex = 0;
                    checkTcsdTaste(checkedTcsdList);

                } else {
                    EventBus.getDefault().post(new ToastEvent("请先选择套餐项", false));
                }
            }
        });

        setupView();

        return mBinding.getRoot();
    }

    private void setupView() {
        // 套餐主项
        Tcsd main = mMeal.getMainTcsd();
        FoodHelper.setCoverImage(main.getImgNo(), mBinding.coverView);
        FoodHelper.setPrice(main, mBinding.priceDescView);
        mBinding.nameView.setText(main.getXmmc1());

        MealChild mealChild = mMeal.getMealChild();

        // 套餐已选择项
        GridLayoutManager layoutManager1 = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
//        LinearLayoutManager layoutManager1 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        mBinding.recyclerView1.setLayoutManager(layoutManager1);
        mBinding.recyclerView1.setHasFixedSize(true);
        mBinding.recyclerView1.setAdapter(new MealCheckedAdapter(mealChild.getMealChildCheckedList()));

        // 套餐子项选择
        if (mMeal.getMultiItemList().size() > 0) {
            mBinding.mealChildLayout.setVisibility(View.VISIBLE);

            LinearLayoutManager layoutManager2 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
            mBinding.recyclerView2.setLayoutManager(layoutManager2);
            mBinding.recyclerView2.setHasFixedSize(true);
            mBinding.recyclerView2.setNestedScrollingEnabled(true);
            mBinding.recyclerView2.setAdapter(new MealVAdapter(mealChild.getMealChildGroupAndMealChildCheckedList()));
        } else {
            mBinding.mealChildLayout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        FoodMenu.getInstance().addObserver(mDataUpdateObserver);
    }

    @Override
    public void onStop() {
        super.onStop();
        FoodMenu.getInstance().deleteObserver(mDataUpdateObserver);
    }

    private void checkTcsdTaste(List<Tcsd> checkedTcsdList) {
        List<Tcsd> tasteTcsdList = Meal.getHasTateTcsdList(checkedTcsdList);

        if (tasteTcsdList.size() == 0) {
            commitTcsdData(checkedTcsdList);

        } else {
            checkTcsdTaste2(checkedTcsdList, tasteTcsdList);
        }
    }

    private void checkTcsdTaste2(List<Tcsd> checkedTcsdList, List<Tcsd> tasteTcsdList) {
        for (int i = 0; i < tasteTcsdList.size(); i++) {
            if (mIndex == i) {
                Tcsd tcsd = tasteTcsdList.get(i);

                TasteDialogFragment fragment = TasteDialogFragment.newInstance(tcsd);
                //noinspection ConstantConditions
                fragment.show(getFragmentManager(), null);
                fragment.setOnClickListener(() -> {
                    mIndex++;
                    if (mIndex < tasteTcsdList.size()) {
                        checkTcsdTaste2(checkedTcsdList, tasteTcsdList);
                    } else {
                        commitTcsdData(checkedTcsdList);
                    }
                });

                break;
            }
        }
    }

    private void commitTcsdData(List<Tcsd> checkedTcsdList) {
        EventBus.getDefault().post(new ToastEvent(mMeal.getMainTcsd().getXmmc1() + " +1"));
        OrderList.getInstance().addMeal(mMeal.getMainTcsd(), checkedTcsdList, null);

        if (mOnClickListener != null) {
            mOnClickListener.onCloseClick();
        }
    }

    private OnClickListener mOnClickListener;

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    public interface OnClickListener {
        void onCloseClick();
    }
}
